﻿/*
Copyright (C) 2009 Dumitru Condrea

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

var interval_id = 0;
var detailsView=null;

plugin.onAddCustomMenuItems = AddCustomMenuItems;

function AddCustomMenuItems(menu) {
    menu.AddItem(strRefresh, 0, onItemRefreshClick);
    //menu.AddItem(strShowChart, 0, onItemShowChartClick);
    //menu.AddItem(strCopyToClipboard, 0, onItemCopyToClipboardClick);
    //menu.AddItem(strCheckForUpdate, 0, runcheckupdate);
    menu.AddItem(strVisitWebSite, 0, onItemVisitWebSiteClick);
}

function onItemShowChartClick(){
  plugin.ShowDetailsView(detailsView,  // The DetailsView object
      strChartTitle,      // The title
      gddDetailsViewFlagNone,  // Flags
      onDetailsViewFeedback);  // The handler to call when details view closes
  //menu.SetItemStyle(strShowChart, gddMenuItemFlagChecked);
}

function onDetailsViewFeedback(){

}

function onItemVisitWebSiteClick(){
    framework.openUrl(GADGET_AUTHOR_WEBSITE);
}

function view_OptionsChanged() {
    if (event.propertyName == 'Min') {
				view.clearInterval(interval_id);
        interval_id = view.setInterVal("pRequest()", parseInt(options.getValue("Min")) * 60000);
    } else {
        rate_updown.src = '';
        lblDiff.visible = false;
    }

    pRequest();
}

function onItemRefreshClick() {
    pRequest();
}

var ie=null; 

function onItemCopyToClipboardClick() {
    var output = "" + lblExName1.innerText + "/" + lblExName2.innerText + " " + lblExRate.innerText + " (" + lblDiff.innerText + ") " + lblExTime.innerText;
    copyToClipboard(output);
//    function copyToClipboard(s) { view.clipboardData.setData('Text', s); }
    function copyToClipboard(s) {  if (ie==null){ ie = new ActiveXObject("InternetExplorer.Application"); ie.Navigate("about:blank"); } ie.document.parentWindow.clipboardData.setData("Text",x);  }
}


function view_onOpen() {
  detailsView = new DetailsView();

  // Create the details view and set its content.
  detailsView.SetContent(
      "",             // Item's displayed website/news source.
      undefined,      // Time created
      "chart.xml",  // The XML file
      false,          // Whether time is shown as absolute time
      0);             // Content layout flags

    var intMin = 1;
    if (options.exists("Min")) {
        intMin = parseInt(options("Min"), intMin);
    } else {
        options("Min") = intMin;
    }

    if (!options.exists("C1")) {
        options.add("C1", "GBP");
    }

    if (!options.exists("C2")) {
        options.add("C2", "MDL");
    }

    lblExRate.innerText = strWait;
    pRequest();
    //view.clearInterval(interval_id); //????
    interval_id = view.setInterVal("pRequest();", intMin * 60000);
    //pRequest();
}

function pRequest(url) {
    if (!options.exists("C1") || !options.exists("C2")) {
        return;
    }
    view.caption = "{0}/{1}".format(options("C1"), options("C2"));
    var url = "http://finance.yahoo.com/q?s={0}{1}%3Dx".format(options("C1"), options("C2"));
    lblExName1.innerText = options("C1").toUpperCase();
    lblExName2.innerText = options("C2").toUpperCase();

    var http = new XMLHttpRequest;
    http.onreadystatechange = OnData;
    http.open("GET", url, true);
    http.setRequestHeader("If-Modified-Since", "Wed, 15 Nov 1995 00:00:00 GMT");
    try {
        http.send();
    } catch (e) {
        gadget.debug.trace("http.send() throw exception!");
        lblExRate.innerText = strErr;
    }

    function OnData() {
        if (http.readyState != 4) { return; }
        
        var exVal;
        var tmVal;
        var oldExVal;

        var strm = http.responseText;
        if (strm != null && strm.length > 0) {
            oldExVal = lblExRate.innerText;
            var exStr = "<span id=\"yfs_l10_{0}{1}=x\">".format(options("C1").toLowerCase(), options("C2").toLowerCase());
            exVal = strm.substr(strm.indexOf(exStr) + exStr.length, 6);
            var tmStr = "<span id=\"yfs_t10_{0}{1}=x\">".format(options("C1").toLowerCase(), options("C2").toLowerCase());
            tmVal = strm.substr(strm.indexOf(tmStr) + tmStr.length, 10);

            try {
                var fOldVal = parseFloat(oldExVal);
                var fNewVal = parseFloat(exVal);
                if ((fOldVal > 0) && (fNewVal > 0)) {
                    if (fOldVal > fNewVal) {
                        rate_updown.src = "images\\rate_down.gif";
                    }
                    if (fOldVal < fNewVal) {
                        rate_updown.src = "images\\rate_up.gif";
                    }

                    if (fOldVal != fNewVal) {
                        var diff = (fNewVal - fOldVal).toFixed(3);
                        if (diff > 0) {
                            rate_updown.tooltip = "+" + diff;
                        } else {
                            rate_updown.tooltip = diff;
                        }
                        lblDiff.visible = true;
                        lblDiff.innerText = rate_updown.tooltip;
                    }
                }
            } catch (e) {
                rate_updown.src = "";
            }
        } else {
            exVal = strErr;
        }

        lblExRate.tooltip = "{0} ({1})\r\n{2} {3}".format(lblExRate.innerText, lblDiff.innerText, strUpdatedTime, new Date().toLocaleTimeString());
        lblExRate.innerText = exVal;
        lblExTime.innerText = tmVal.trim();
    }
}